﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfKeyFrame.ViewModels;
using static WpfKeyFrame.Views.PublicClasses;

namespace WpfKeyFrame.Views
{
    /// <summary>
    /// Interaction logic for MainProcessWindow
    /// </summary>
    public partial class MainProcessWindow : UserControl
    {
        readonly MainProcessWindowViewModel viewModel;  // 访问ViewModel中的数据
        Storyboard storyboard = new() { RepeatBehavior = RepeatBehavior.Forever };

        public MainProcessWindow()
        {
            InitializeComponent();
            PngImage.Visibility = Visibility.Visible;
            viewModel = this.DataContext as MainProcessWindowViewModel;
        }
        private void QuJingKuang_MouseEnter(object sender, MouseEventArgs e)
        {
            QuJingKuang.StrokeThickness = 3;
        }

        private void QuJingKuang_MouseLeave(object sender, MouseEventArgs e)
        {
            QuJingKuang.StrokeThickness = 1;
        }

        bool _isMousedown = false;
        Point _mouseDownPosition;
        Point _mouseDownControlPosition;

        private void QuJingKuang_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is not Shape control) return;
            _isMousedown = true;
            _mouseDownPosition = e.GetPosition(this);
            _mouseDownControlPosition = new Point(
                double.IsNaN(Canvas.GetLeft(control)) ? 0 : Canvas.GetLeft(control),
                double.IsNaN(Canvas.GetTop(control)) ? 0 : Canvas.GetTop(control));
            control.CaptureMouse();
        }
        private void QuJingKuang_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMousedown)
            {
                Shape control = sender as Shape;
                var pos = e.GetPosition(this);
                var dpos = pos - _mouseDownPosition;
                double localX = (_mouseDownControlPosition.X + dpos.X is > -5 and < 5) ? 0 : _mouseDownControlPosition.X + dpos.X;
                double localY = (_mouseDownControlPosition.Y + dpos.Y is > -5 and < 5) ? 0 : _mouseDownControlPosition.Y + dpos.Y;
                List<int> HorizontalLocal = viewModel.HorizontalLocal;
                List<int> VerticalLocal = viewModel.VerticalLocal;
                if (HorizontalLocal != null && HorizontalLocal.Count > 0)
                {
                    foreach (int row in HorizontalLocal)
                    {
                        if (Math.Abs(_mouseDownControlPosition.Y + dpos.Y - row) < 20)
                        {
                            localY = row;
                            break;
                        }
                    }
                }
                if (VerticalLocal != null && VerticalLocal.Count > 0)
                {
                    foreach (int col in VerticalLocal)
                    {
                        if (Math.Abs(_mouseDownControlPosition.X + dpos.X - col) < 20)
                        {
                            localX = col;
                            break;
                        }
                    }
                }
                Canvas.SetLeft(control, localX);
                Canvas.SetTop(control, localY);

            }
        }

        private void QuJingKuang_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Shape control = sender as Shape;
            _isMousedown = false;
            control?.ReleaseMouseCapture();
        }
        /// <summary>
        /// 文本框获取焦点情况下，用键盘上下方向键、上下换页键改变数值。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTextBoxKeyUp(object sender, KeyEventArgs e)
        {
            if (sender is TextBox textbox)
            {
                int num = int.Parse(textbox.Text);
                if (e.Key == Key.Up) { num++; }
                if (e.Key == Key.PageUp) { num += 10; }
                if (e.Key == Key.Down) { num--; }
                if (e.Key == Key.PageDown) { num -= 10; }
                if (num < 0) num = 0;
                textbox.Text = num.ToString();
            }
        }
        /// <summary>
        /// 点击图像时，将取景框的中心移动到点击位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnImageClick(object sender, MouseButtonEventArgs e)
        {
            var pos = e.GetPosition(PngImage);
            viewModel.QuJingKuangLeft = pos.X - viewModel.QuJingKuangWidth / 2;
            viewModel.QuJingKuangTop = pos.Y - viewModel.QuJingKuangHeight / 2;
        }
        /// <summary>
        /// 动画预览开始播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PreviewButtonClick(object sender, RoutedEventArgs e)
        {
            DoubleAnimationUsingKeyFrames framesX = new();
            DoubleAnimationUsingKeyFrames framesY = new();

            //Storyboard.SetTargetProperty(framesX, new PropertyPath(TranslateTransform.XProperty)); // 有问题，不起作用，为什么？
            //Storyboard.SetTarget(framesX, previewImge);
            Storyboard.SetTargetProperty(framesX, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"));  // 没有问题，起作用。为什么？
            Storyboard.SetTarget(framesX, previewImge);

            //Storyboard.SetTargetProperty(framesY, new PropertyPath(TranslateTransform.YProperty));
            //Storyboard.SetTarget(framesY, priviewTransform);

            Storyboard.SetTargetProperty(framesY, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"));
            Storyboard.SetTarget(framesY, previewImge);

            for (int i = 0; i < viewModel.FrameList.Count; i++)
            {
                var frame = viewModel.FrameList[i];
                frame.FrameBeginTime = TimeSpan.FromMilliseconds(i * 100);
                framesX.KeyFrames.Add(new DiscreteDoubleKeyFrame(frame.FrameLeft * -1, frame.FrameBeginTime));
                framesY.KeyFrames.Add(new DiscreteDoubleKeyFrame(frame.FrameTop * -1, frame.FrameBeginTime));
            }
            storyboard = new Storyboard() { RepeatBehavior = RepeatBehavior.Forever };
            storyboard.Children.Add(framesX);
            storyboard.Children.Add(framesY);
            storyboard.Begin();
            //priviewTransform.SetValue(TranslateTransform.XProperty, -200.0);
            //priviewTransform.SetValue(TranslateTransform.YProperty, -400.0);
        }

        private void StopPreviewButtonClick(object sender, RoutedEventArgs e)
        {
            storyboard.Stop();
        }

        /// <summary>
        /// 列表帧选择改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewSelectChanged(object sender, SelectionChangedEventArgs e)
        {
            var listview = sender as ListView;
            viewModel.SelectedFrames = listview.SelectedItems.Cast<FrameClass>().ToList();
        }

        /// <summary>
        /// 主窗口缩放，用Ctrl+鼠标滚轮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainImageViewBoxMouseWhell(object sender, MouseWheelEventArgs e)
        {
            if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
            {
                e.Handled = true;
                if (e.Delta > 0)
                {
                    MainViewScale.ScaleX += 0.1;
                    MainViewScale.ScaleY += 0.1;

                }
                if (e.Delta < 0)
                {
                    if (MainViewScale.ScaleX > 1)
                    {
                        MainViewScale.ScaleX -= 0.1;
                        MainViewScale.ScaleY -= 0.1;
                    }
                    else
                    {
                        MainViewScale.ScaleX -= 0.05;
                        MainViewScale.ScaleY -= 0.05;
                    }
                    if (MainViewScale.ScaleX < 0.05) MainViewScale.ScaleX = 0.05;
                    if ( MainViewScale.ScaleY < 0.05) MainViewScale.ScaleY = 0.05;
                }
            }
        }

        /// <summary>
        /// 显示比例恢复到100%
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Zoom100Click(object sender, RoutedEventArgs e)
        {
            MainViewScale.ScaleX = 1.0;
            MainViewScale.ScaleY = 1.0;
        }
    }
}
